<!--私信组件-->
<template>
    <div class="private-message-container">
        <div class="message-layout">
            <!-- 联系人列表 -->
            <div class="contacts">
                    <div v-for="item in contacts" :key="item.userId">
                        <div @click="loadChatHistory(item.user_id)"
                             style="display: flex; align-items: center;border-bottom: 1px #f5f4f1 solid; padding: 10px 0; cursor: pointer"
                             :class="{ active: item.userId === route.params.id }">
                            <el-avatar :src="item.profile_photo_path" style="margin-left: 10px; margin-right: 20px"></el-avatar>
                            <div class="username">{{item.username}}</div>
                        </div>
<!--                        <div v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</div>&lt;!&ndash; 未读消息数量 &ndash;&gt;-->
                    </div>
            </div>

            <!-- 聊天区域 -->
            <div class="chat-area" v-if="route.params.id">
                <div class="chat-header">
                    <div style="margin: 0 auto; font-size: 16px; font-weight: 600">{{receiver.username}}</div><!-- 用户名 -->
                </div>
                <div class="chat-messages">
                    <el-empty v-if="messages.length === 0" description="暂无消息"></el-empty>
                    <div v-else class="message-item" v-for="message in messages" :key="message.messageId">
                        <div class="message-content" :class="{ 'right': message.senderId === user.user_id }"> <!-- 发送者为自己时，消息靠右 -->
                            <el-avatar :src="message.sender?.profile_photo_path" class="message-avatar" v-if="message.senderId !== user.user_id"></el-avatar>
                            <div class="message-text">
                                <div class="text">{{ message.content }}</div>
<!--                                <div class="time">{{ message.createdAt }}</div>-->
                            </div>
                            <el-avatar :src="message.sender?.profile_photo_path" class="message-avatar" v-if="message.senderId === user.user_id"></el-avatar>
                        </div>
                    </div>
                </div>

                <div class="chat-input">
                    <el-input
                        v-model="messageContent"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入消息内容"
                        @keyup.enter.native="sendMessage"
                    ></el-input>
                    <el-button type="primary" @click="sendMessage" style="margin-left: 20px">发送</el-button>
                </div>
            </div>

            <!-- 选择联系人提示 -->
            <div class="no-selection" v-else>
                <el-empty description="请选择一位联系人开始聊天"></el-empty>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import router from "@/router/index.js";

const { proxy } = getCurrentInstance();
//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}
const route = useRoute()
const receiverId = route.params.id;  // 当前选择的联系人id，从路径中获取
const receiver = ref({})
const userId = user.user_id; // 当前用户 ID
const messages = ref([]);  // 聊天记录
const messageContent = ref('');  // 发送的消息内容
const unreadCount = ref(0);  // 未读消息数量
const contacts = ref([]);  // 已有过私信的联系人列表


// WebSocket消息处理
const handleMessage = (e) => {
    const msg = e.detail.data;
    console.log(msg)
    if (msg.receiverId === userId) {
        messages.value.push(msg);
        // loadChatHistory(msg.receiverId)
        console.log(msg.receiverId)
    }
};

onMounted(() => {
    if (!user.token) {
        ElMessage.error('请先登录');
        console.log(user.token)
        return;
    }
    // 初始化WebSocket连接
    proxy.$websocket.initWebsocket(user.token);
    // 监听消息事件
    window.addEventListener('onmessageWs', handleMessage);
    // 加载历史聊天记录
    loadChatHistory(receiverId);
    getContacts()

});

onUnmounted(() => {
    proxy.$websocket.close(); // 断开连接
    window.removeEventListener('onmessageWs', handleMessage);
});

const state = reactive({
    pageNum: 1,
    pageSize: 20,
})

// 加载历史聊天记录（需后端接口支持）
const loadChatHistory = async (receiverId) => {
    await router.push('/messagecenter/privatemessage/' + receiverId)
    try {
        const userRes = await request.get('/api/users/getUser', {
            params: {
                userId: receiverId
            }
        });
        if (userRes.code === '200') {
            receiver.value = userRes.data
            console.log("获取接收用户成功")
        }
        const res = await request.get('/api/message/chat', {
            params: {
                senderId: userId,
                receiverId:receiverId,
                messageType: 'PRIVATE',
                pageNum: state.pageNum,
                pageSize: state.pageSize,
            }
        });
        if (res.code === '200') {
            messages.value = res.data.list; // 最新消息在底部
            console.log(messages.value)
            console.log('获取聊天记录成功')
        }
    } catch (error) {
        console.error('加载聊天记录失败', error);
    }
};
// 发送消息
const sendMessage = () => {
    if (!messageContent.value.trim()) return;

    const message = {
        senderId: user.user_id,
        receiverId: receiverId,
        sender: {
            profile_photo_path: user.profile_photo_path
        },
        content: messageContent.value.trim(),
        messageType: 'PRIVATE', // 私信类型
    };

    proxy.$websocket.sendMessage(JSON.stringify(message));
    messages.value.push(message); // 本地先添加消息（需根据后端返回调整）
    messageContent.value = ''; // 清空输入
};

// 获取已联系人列表
const getContacts = () => {
    request.get('/api/message/contacts', {
        params: {
            userId: user.user_id
        }
    }).then(res => {
        if (res.code === '200') {
            contacts.value = res.data
            console.log("获取用户列表成功")
        }
    })
}


// 滚动到底部
const scrollToBottom = () => {

};
</script>

<style scoped>
.private-message-container {
    /*height: calc(100vh - 60px);*/
}

.message-layout {
    display: flex;
    height: 100%;
}

.contacts {
    width: 240px;
    border-right: 1px solid #ebeef5;
    padding: 10px;
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: 550;
    font-size: 18px;
    margin-left: 20px;
}

.last-message {
    font-size: 12px;
    color: #909399;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.message-time {
    font-size: 12px;
    color: #909399;
}

.unread-badge {
    background-color: #ff4d4f;
    color: white;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-left: 10px;
}

.active {
    background-color: #f5f7fa;
}

.chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    height: 50px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    padding: 0 15px;
    font-weight: 500;
}

.chat-messages {
    /*flex: 1;*/
    overflow-y: auto;
    padding: 10px;
    max-height: 400px;
    min-height: 350px;
}

.message-item {
    margin-bottom: 15px;
}

.message-content {
    display: flex;
    align-items: flex-end;
}

.message-content.right {
    justify-content: flex-end;
}

.message-avatar {
    margin-right: 10px;
}

.message-content.right .message-avatar {
    margin-right: 0;
    margin-left: 10px;
}

.message-text {
    max-width: 70%;
    background-color: #f0f2f5;
    padding: 8px 12px;
    border-radius: 6px;
    position: relative;
}

.message-content.right .message-text {
    background-color: #409eff;
    color: white;
}

.time {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.message-content.right .time {
    text-align: right;
    color: #fffefb;
}

.chat-input {
    padding: 15px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.no-selection {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>